package com.szholly.utils.common.iecache;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义静态资源IE缓存处理
 */
public class StaticSourceModExpiresFilter implements javax.servlet.Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// 保存30天，30天 * 24小时 * 60分钟 * 60秒
		checkHeaderCache(2592000L, 
				(HttpServletRequest)request, (HttpServletResponse)response);
		chain.doFilter(request, response);
	}
	
	private static boolean checkHeaderCache(long adddays, 
			HttpServletRequest request, HttpServletResponse response) {
		// convert seconds to ms.
		long adddaysM = adddays * 1000;
		long header = request.getDateHeader("If-Modified-Since");
		long now = System.currentTimeMillis();
		if (header > 0 && adddaysM > 0) {
//			if (modelLastModifiedDate > header) {
//				// adddays = 0; // reset
//				response.setStatus(HttpServletResponse.SC_OK);
//				return true;
//			}
			if (header + adddaysM > now) {
				// during the period happend modified
				response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
				return false;
			}
		}

		// if over expire data, see the Etags;
		// ETags if ETags no any modified
//		String previousToken = request.getHeader("If-None-Match");
//		if (previousToken != null && previousToken.equals(Long.toString(modelLastModifiedDate))) {
//			// not modified
//			response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
//			return false;
//		}
		// if th model has modified , setup the new modified date
//		response.setHeader("ETag", Long.toString(modelLastModifiedDate));
		setRespHeaderCache(adddays, request, response);
		return true;
	}

	private static boolean setRespHeaderCache(long adddays, HttpServletRequest request, HttpServletResponse response) {
		long adddaysM = adddays * 1000;
		String maxAgeDirective = "max-age=" + adddays;
		response.setHeader("Cache-Control", maxAgeDirective);
		response.setStatus(HttpServletResponse.SC_OK);
		response.addDateHeader("Last-Modified", System.currentTimeMillis());
		response.addDateHeader("Expires", System.currentTimeMillis() + adddaysM);
		return true;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}
}
